package com.yiba.vpn.util;

import java.util.HashMap;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloopen.rest.sdk.CCPRestSmsSDK;

public class SMSSendUtil {

    // 主帐号,对应开官网发者主账号下的 ACCOUNT SID
    private String accountSid = "aaf98f894f16fdb7014f1bcff43906e0";
    // 主帐号令牌,对应官网开发者主账号下的 AUTH TOKEN
    private String accountToken = "b84e14f47d7b453b87e2c5052d89f59f";
    // 应用Id，在官网应用列表中点击应用，对应应用详情中的APP ID
    // 在开发调试的时候，可以使用官网自动为您分配的测试Demo的APP ID
    // private $appId = "8aaf07085aabcbbd015ad2163ece0ce6";
    private String appId = "aaf98f894f16fdb7014f1bd152f906ed";
    // 请求地址
    // 沙盒环境（用于应用开发调试）：sandboxapp.cloopen.com
    // 生产环境（用户应用上线使用）：app.cloopen.com
    // private $serverIP = "app.cloopen.com";
    private String serverIP = "sandboxapp.cloopen.com";
    // 请求端口，生产环境和沙盒环境一致
    private String serverPort = "8883";

    //private String templateId = "31708";
    private String templateId = "223019";

    private Logger logger = LoggerFactory.getLogger(SMSSendUtil.class);

    /**
     * @Title: send @Description: 发送短信 @param @param phoneNu 设定文件 @return void
     * 返回类型 @throws
     */
    public int send(String phoneNu) {

        //RedisService redisService = new RedisService();
        // 校验手机号码正确性 ;
        if (!checkPhoneNu(phoneNu)) {
            return -2;
        }

        HashMap<String, Object> result = null;

        // 初始化SDK
        CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
        restAPI.init(serverIP, serverPort);
        restAPI.setAccount(accountSid, accountToken);
        restAPI.setAppId(appId);
        //生成随机的验证码 4位数
        String verCode = createVerifyCode();
        result = restAPI.sendTemplateSMS(phoneNu, templateId, new String[]{verCode, "5"});
        if ("000000".equals(result.get("statusCode"))) {
            logger.info("-------------------------短信发送成功 -----------------------");
            //Redis.use("redis").setex(phoneNu, 300, verCode);
            return 0;
        } else {
            logger.info("-------------------------短信发送失败 {" + result.get("statusCode") + "}-----------------------");
            return -1;
        }
    }

    public Boolean checkPhoneNu(String phoneNu) {
        String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(phoneNu);
        return m.matches();
    }

    /**
     * @param @param  length
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: createVerifyCode
     * @Description: 随机生成4位数验证码
     */
    protected String createVerifyCode() {
        String str = "0123456789";
        StringBuilder sb = new StringBuilder(4);
        for (int i = 0; i < 4; i++) {
            char ch = str.charAt(new Random().nextInt(str.length()));
            sb.append(ch);
        }
        return sb.toString();
    }

    public int sendMsg(String phoneNu, String templateid ,String [] data) {

        //RedisService redisService = new RedisService();
        // 校验手机号码正确性 ;
        if (!checkPhoneNu(phoneNu)) {
            return -2;
        }

        HashMap<String, Object> result = null;

        // 初始化SDK
        CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
        restAPI.init(serverIP, serverPort);
        restAPI.setAccount(accountSid, accountToken);
        restAPI.setAppId(appId);
        result = restAPI.sendTemplateSMS(phoneNu, templateid, data);
        if ("000000".equals(result.get("statusCode"))) {
            logger.info("-----------------------短信发送成功 -----------------------");
            //Redis.use("redis").setex(phoneNu, 300, verCode);
            return 0;
        } else {
            logger.info("-----------------------短信发送失败 {" + result.get("statusCode") + "}-----------------------");
            return -1;
        }
    }
    public static void main(String[] args) throws Exception {
        SMSSendUtil uu = new SMSSendUtil();

        int sendMsg = uu.sendMsg("15869177527","236212",new String[]{"123456","10"});
        System.out.println(sendMsg);

    }
}
